import 'package:faker/common/application.dart';
import 'package:faker/events/homescrollevent.dart';
import 'package:faker/events/updatearticle.dart';
import 'package:faker/i18n/i18n.dart';
import 'package:faker/models/local_rss.dart';
import 'package:faker/provider/local_rss_provider.dart';
import 'package:faker/res/style.dart';
import 'package:faker/screen/readlater_rss_screen.dart';
import 'package:faker/utils/route_util.dart';
import 'package:faker/utils/toast_util.dart';
import 'package:faker/widgets/add_rss.dart';
import 'package:faker/widgets/base_widget.dart';
import 'package:faker/widgets/item_rss_list.dart';
import 'package:faker/widgets/refresh_helper.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:intl/intl.dart' as intl;
import 'package:pull_to_refresh/pull_to_refresh.dart';

import 'favorite_rss_screen.dart';

/// 首页
class HomeScreen extends BaseWidget {
  @override
  BaseWidgetState<BaseWidget> attachState() {
    return HomeScreenState();
  }
}

class HomeScreenState extends BaseWidgetState<HomeScreen> {
  /// 首页文章列表数据
  List<LocalRss> _rssBean = new List();

  /// listview 控制器
  ScrollController _scrollController = new ScrollController();

  /// ListItem 左右滑动控制器
  final SlidableController slidableController = SlidableController();

  /// 查找Rss 控制器
  final _txtcontroller = TextEditingController();

  /// 是否显示悬浮按钮
  bool _isShowFAB = false;

  FocusNode _txtFocusNode = FocusNode();

  String searchString;

  RefreshController _refreshController =
      new RefreshController(initialRefresh: false);

  //退出2次确认;
  Future<bool> _onWillPop() {
    return showDialog(
          context: context,
          builder: (context) => new AlertDialog(
            title: new Text('提示',
                style: TextStyle(color: Colors.black, fontSize: 18.0)),
            content: new Text('您确定要退出程序吗?',
                style: TextStyle(color: Colors.black, fontSize: 18.0)),
            actions: <Widget>[
              new FlatButton(
                onPressed: () => Navigator.of(context).pop(false),
                child: new Text('否',
                    style: TextStyle(color: Colors.black, fontSize: 18.0)),
              ),
              Center(
                child: Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: new FlatButton(
                    onPressed: () => {
                      if (Navigator.canPop(context))
                        SystemChannels.platform
                            .invokeMethod('SystemNavigator.pop'),
                    },
                    child: new Text('是',
                        style: TextStyle(color: Colors.black, fontSize: 18.0)),
                  ),
                ),
              ),
            ],
          ),
        ) ??
        false;
  }

  @override
  void initState() {
    //getRssData();
    super.initState();
    setAppBarVisible(false);
    this.registerHomeScrollEvent();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    showLoading().then((value) {
      getRssData();
    });

    _scrollController.addListener(() {
      /// 滑动到底部，加载更多
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        // getMoreArticleList();
      }
      if (_scrollController.offset < 200 && _isShowFAB) {
        setState(() {
          _isShowFAB = false;
        });
      } else if (_scrollController.offset >= 200 && !_isShowFAB) {
        setState(() {
          _isShowFAB = true;
        });
      }
    });
  }

  void ListViewMove() {
    print("move");
    _scrollController.jumpTo(_scrollController.offset + 0.1);
  }

  /// 注册改变事件
  void registerHomeScrollEvent() async {
    Application.eventBus
        .on<HomeScrollEvent>()
        .listen((event) => this.ListViewMove());
  }

  /// getRss Data
  Future getRssData() async {
    _rssBean.clear();
    LocalRssProvider provider = new LocalRssProvider();
    List list = await provider.getAllLocalRssProvider();
    if (list.length > 0) {
      //数据库有数据
      showContent().then((value) {
        _refreshController.refreshCompleted(resetFooterState: true);
        setState(() {
          _rssBean.addAll(LocalRss.fromMapList(list));

          ///刷新文章;
          Future.delayed(Duration(seconds: 1), () {
            Application.eventBus.fire(UpdateArticleEvent());
          });
        });
      });
    } else
      showEmpty();
  }

  @override
  AppBar attachAppBar() {
    return AppBar(title: Text(""));
  }

  @override
  Widget attachContentWidget(BuildContext context) {
    return WillPopScope(
        onWillPop: _onWillPop,
        child: CustomScrollView(
          physics: ScrollPhysics(),
          slivers: <Widget>[
            SliverToBoxAdapter(
              child: Container(
                height: MediaQuery.of(context).size.height,
                width: MediaQuery.of(context).size.width,
                decoration: BoxDecoration(
                    gradient: LinearGradient(
                        colors: [
                      Theme.of(context).backgroundColor,
                      Theme.of(context).primaryColorLight,
                    ],
                        begin: Alignment.bottomCenter,
                        end: Alignment.topCenter,
                        tileMode: TileMode.clamp)),
                child: Column(
                  children: <Widget>[
                    SizedBox(
                      height: 42,
                    ),
                    Padding(
                      padding: EdgeInsets.symmetric(horizontal: 20.0),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: <Widget>[
                          Text(
                              intl.DateFormat('yyyy-MM-dd')
                                  .format(DateTime.now())
                                  .toString(),
                              style: TextStyle(
                                color: Theme.of(context).textSelectionColor,
                                fontSize: 46.0,
                                fontFamily: fontName,
                                letterSpacing: 1.0,
                              )),
                          /*
                          IconButton(
                            icon: Icon(
                              option,
                              size: 12.0,
                              color: Colors.blueGrey,
                            ),
                            onPressed: () {},
                          )
                        */
                        ],
                      ),
                    ),
                    SizedBox(height: 20.0),
                    Divider(
                      color: Colors.black12,
                      height: 1.0,
                      indent: 75,
                      //endIndent: 20,
                    ),
                    Card(
                      margin: EdgeInsets.only(bottom: 2.0),
                      elevation: 0,
                      child: GestureDetector(
                        onTap: () {
                          RouteUtil.push(context, FavRssScreen());
                        },
                        child: ListTile(
                          leading: Icon(
                            Icons.chrome_reader_mode,
                            color: Theme.of(context).accentColor,
                            size: 24,
                          ),
                          title: Text(S.of(context).recentlyRead),
                          trailing: Icon(
                            Icons.arrow_forward_ios,
                            size: 18,
                            color: kGrey600,
                          ),
                        ),
                      ),
                    ),
                    Divider(
                      color: Colors.black12,
                      height: 1.0,
                      indent: 75,
                      //endIndent: 20,
                    ),
                    Card(
                      margin: EdgeInsets.only(bottom: 2.0),
                      elevation: 0,
                      child: GestureDetector(
                        onTap: () {
                          RouteUtil.push(context, ReadLaterRssScreen());
                        },
                        child: ListTile(
                          leading: Icon(
                            Icons.bookmark,
                            color: Theme.of(context).accentColor,
                            size: 24,
                          ),
                          title: Text(S.of(context).readLater),
                          trailing: Icon(
                            Icons.arrow_forward_ios,
                            size: 18,
                            color: kGrey600,
                          ),
                        ),
                      ),
                    ),
                    Divider(
                      color: Colors.black12,
                      height: 1.0,
                      indent: 75,
                      //endIndent: 20,
                    ),
                    /*
                    new Card(
                        margin: EdgeInsets.only(bottom: 2.0),
                        elevation: 0,
                        child: new Container(
                          child: new Row(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: <Widget>[
                              SizedBox(
                                width: 5.0,
                              ),
                              Icon(
                                Icons.search,
                                color: Colors.grey,
                              ),
                              Expanded(
                                child: TextField(
                                  focusNode: _txtFocusNode,
                                  autofocus: false,
                                  enabled: true,
                                  controller: _txtcontroller,
                                  style: TextStyle(
                                    fontFamily: fontName,
                                    fontSize: 16,
                                    color: Theme.of(context).textSelectionColor,
                                  ),
                                  decoration: InputDecoration.collapsed(
                                    hintText: S.of(context).searchRss,
                                  ),
                                  maxLines: 1,
                                ),
                              ),
                              new IconButton(
                                icon: new Icon(Icons.cancel),
                                color: Colors.grey,
                                iconSize: 18.0,
                                onPressed: () {
                                  _txtcontroller.clear();
                                  FocusScope.of(context)
                                      .requestFocus(FocusNode());
                                },
                              ),
                            ],
                          ),
                        )),
                    Divider(
                      color: Colors.black12,
                      height: 1.0,
                      indent: 75,
                      //endIndent: 20,
                    ),
                     */
                    SizedBox(height: 20.0),
                    Padding(
                      padding: EdgeInsets.symmetric(horizontal: 20.0),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: <Widget>[
                          Text(S.of(context).myRss,
                              style: TextStyle(
                                color: Theme.of(context).textSelectionColor,
                                fontSize: 46.0,
                                fontFamily: fontName,
                                letterSpacing: 1.0,
                              )),
                        ],
                      ),
                    ),
                    Expanded(
                      child: SmartRefresher(
                        enablePullDown: true,
                        enablePullUp: false,
                        header: MaterialClassicHeader(),
                        footer: RefreshFooter(),
                        controller: _refreshController,
                        onRefresh: getRssData,
                        onLoading: getRssData,
                        child: ListView.builder(
                          itemBuilder: itemView,
                          shrinkWrap: true,
                          physics: new AlwaysScrollableScrollPhysics(),
                          controller: _scrollController,
                          itemCount: _rssBean.length,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ));
  }

  @override
  void onClickErrorWidget() {
    showLoading().then((value) {
      getRssData();
    });
  }

  /// ListView 中每一行的视图
  Widget itemView(BuildContext context, int index) {
    LocalRss item = _rssBean[index];
    return ItemRssList(
      item: item,
      slidableController: slidableController,
      edit: (item) {
        RouteUtil.push(
            context,
            AddRssScreen(
              editKey: 1,
              icon: "",
              rss: item,
            ));
      },
      delete: (id) async {
        LocalRssProvider provider = new LocalRssProvider();
        await provider.delete(id);
        T.show(msg: S.of(context).successDelete);
        getRssData();
      },
    );
  }

  @override
  void dispose() {
    _refreshController.dispose();
    _scrollController.dispose();
    _txtcontroller.dispose();
    super.dispose();
  }
}
